﻿using System;
using System.Collections.Generic;
using System.Text;
using Comm.PublicClass;
using System.Security.Cryptography;
using System.IO;
using System.Threading;


namespace WsProtocol.IEC62056.DataTypeClass{
   

    public class Data 
    {
        public static Encryption encryption = null;
        //用于数据组织,不带数据类型字节,字符串类型不带长度字节
        public static string GetPreFormatValue(ElementData eleNode, int Typetag, ref string errorinfo)//, ref string sdtype
        {
            string FormatValue = string.Empty;
            if (string.IsNullOrEmpty(eleNode.DataType)) return FormatValue;
           
            try
            {
                string sDtype = Typetag == 0 ? eleNode.DataType : eleNode.DataTypeDIY;
                enumData dtype = (enumData)Enum.Parse(typeof(enumData), sDtype);
                switch (dtype)
                {
                    case enumData.NULL:
                        
                        break;
                    case enumData.array:
                        FormatValue = Array.GetPreFormatValue(eleNode,ref errorinfo);
                        break;
                    case enumData.structure:
                        FormatValue = Structure.GetPreFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.boolean:
                        FormatValue = Bool.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.bit_string:
                        FormatValue = bstring.GetFormatValue(eleNode.SetValue, eleNode.DataLen, ref errorinfo);
                        break;
                    case enumData.octet_string:
                        FormatValue = octString.GetFormatValue(eleNode.SetValue, eleNode.DataLen, ref errorinfo);
                        break;
                    case enumData.visible_string:
                        FormatValue = visiblestring.GetFormatValue(eleNode.SetValue, eleNode.DataLen, ref errorinfo);
                        break;
                    case enumData.utf8_string:
                        FormatValue = UTF8string.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.bcd:
                        FormatValue = BCD.GetPreFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.integer:
                        FormatValue = integer.GetFormatValue(eleNode, ref errorinfo); 
                        break;
                    case enumData.Long:
                        FormatValue = ilong.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.double_long:
                        FormatValue = doublelong.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.long64:
                        FormatValue = long64.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.unsigned:
                        FormatValue = unsigned.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.long_unsigned:
                        FormatValue = longunsigned.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.double_long_unsigned:
                        FormatValue = doublelongunsigned.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.long64_unsigned:
                        FormatValue = long64unsigned.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.Enum:
                        FormatValue = ProEnum.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.float32:
                    case enumData.float64:
                        FormatValue = float32.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.date_time:
                        FormatValue = datetime.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.date:
                        FormatValue = date.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.time:
                        FormatValue = time.GetFormatValue(eleNode, ref errorinfo);
                        break;                  
                    case enumData.SUnit:
                        FormatValue = SUnit.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.CAD:
                        FormatValue = CAD.GetFormatValue(eleNode, ref errorinfo); 
                        break;
                    case enumData.ScalerUnit:
                        FormatValue = ScalerUnit.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.COMDCB:
                        FormatValue = COMDCB.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.OBIS:
                        FormatValue = OBIS.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.TokenEnterData:
                        FormatValue = TokenEnterData.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.MKEncrypt:
                        FormatValue = MKEncrypt.GetFormatValue(eleNode, ref errorinfo);
                        break; 
                    case enumData.ModuleParas:
                        FormatValue = ModuleParas.GetFormatValue(eleNode, ref errorinfo);
                        break;
                }                
                return FormatValue;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }

        }


        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            string FormatValue = string.Empty;
            if (!string.IsNullOrEmpty(eleNode.DataTypeDIY)) //如果有自定义格式，先按自定义格式组织数据
            {
                FormatValue = eleNode.SetValue = Data.GetPreFormatValue(eleNode, 1, ref errorinfo);
            }
            if (string.IsNullOrEmpty(eleNode.DataType)) return FormatValue;           

            try
            {
                enumData dtype = (enumData)Enum.Parse(typeof(enumData), eleNode.DataType);
                switch (dtype)
                {
                    case enumData.NULL:                        
                        break;
                    case enumData.array:
                        FormatValue = Array.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.structure:
                        FormatValue = Structure.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.boolean:
                        FormatValue = Bool.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.bit_string:
                        FormatValue = bstring.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.octet_string:
                        FormatValue = octString.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.visible_string:
                        FormatValue = visiblestring.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.utf8_string:
                        FormatValue = UTF8string.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.bcd:
                        FormatValue = BCD.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.integer:
                        FormatValue = integer.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.Long:
                        FormatValue = ilong.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.double_long:
                        FormatValue = doublelong.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.long64:
                        FormatValue = long64.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.unsigned:
                        FormatValue = unsigned.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.long_unsigned:
                        FormatValue = longunsigned.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.double_long_unsigned:
                        FormatValue = doublelongunsigned.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.long64_unsigned:
                        FormatValue = long64unsigned.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.Enum:
                        FormatValue = ProEnum.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.float32:
                    case enumData.float64:
                        FormatValue = float32.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.date_time:
                        FormatValue = datetime.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.date:
                        FormatValue = date.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.time:
                        FormatValue = time.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.CHOICE:
                        FormatValue = CHOICE.GetFormatValue(eleNode, ref errorinfo);
                        return FormatValue;
                        break;
                    case enumData.SUnit:
                        FormatValue = SUnit.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.CAD:
                        FormatValue = CAD.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.ScalerUnit:
                        FormatValue = ScalerUnit.GetFormatValue(eleNode, ref errorinfo);
                        break;
                    case enumData.COMDCB:
                        FormatValue = COMDCB.GetFormatValue(eleNode, ref errorinfo);
                        break;             
                }
                return MyConvert.DecToHex(((int)dtype).ToString(), 2) + FormatValue;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }

        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            int iResult = 0;
            string newframeData = frameData;
            string oldframedata = frameData;
            try
            {                
                enumData dtype = (enumData)Convert.ToInt32(newframeData.Substring(0, 2), 16);
                eleNode.DataType = dtype.ToString();
                newframeData = newframeData.Remove(0, 2); //删除数据类型标志

                oldframedata = newframeData;  //记录一下解析前的数据  shaunwang 2019-10-28

                iResult = AnalizeDtypeData(ref newframeData, eleNode, dtype, 0, ref errorinfo);
                frameData = newframeData;
                if (iResult >= 0 && !string.IsNullOrEmpty(eleNode.DataTypeDIY))
                {
                    dtype = (enumData)Enum.Parse(typeof(enumData), eleNode.DataTypeDIY);
                    if (!string.IsNullOrEmpty(eleNode.FrameValue))
                    {
                        string tmpframeData = eleNode.FrameValue;
                        iResult = AnalizeDtypeData(ref tmpframeData, eleNode, dtype, 1, ref errorinfo);  //用自定义格式再解析一遍 
                    }
                }
                //if (!string.IsNullOrEmpty(eleNode.ShowFormat))
                //    eleNode.ReadValue = Explaindata1(eleNode.ReadValue, InitFormat(eleNode.ShowFormat));
                if (!string.IsNullOrEmpty(errorinfo))
                    errorinfo += "["
                               + oldframedata
                               + "]";
                return iResult;
            }
            catch (Exception ex)
            {
                errorinfo = "数据有缺损"
                          + "["
                          + oldframedata
                          + "]";
                frameData = newframeData;
                return -1;
            }
        }

        //Typetag为1时，只解析纯数据，不再判断长度字节等。 为0时要按协议所支持的格式去解析，有长度或其他辅助信息字节
        public static int AnalizeDtypeData(ref string frameData, ElementData eleNode, enumData dtype,int Typetag, ref string errorinfo)
         {
            
             int iResult = 0;
             string oldframedata = frameData;  //记录一下解析前的数据  shaunwang 2019-10-28
             try
             {
                 if (Typetag == 0)
                     eleNode.ReadValue = eleNode.FrameValue = ""; //清空一下解析数据
                 
                 switch (dtype)
                 {
                     case enumData.NULL:
                         eleNode.ReadValue = "NULL";
                         break;
                     case enumData.array:
                         iResult = Array.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.structure:
                         if (Typetag == 1)
                         {                            
                             iResult = Structure.AnalizeData(eleNode, ref errorinfo);
                         }
                         else
                            iResult = Structure.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.boolean:
                         iResult = Bool.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.bit_string:
                         if (Typetag == 1)
                         {                             
                             iResult = bstring.AnalizeData(eleNode);                            
                         }
                         else
                             iResult = bstring.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.octet_string:
                         if (Typetag == 1)
                         {
                             iResult = octString.AnalizeDataSpecial(ref frameData, eleNode, ref errorinfo);
                         }
                         else
                            iResult = octString.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.visible_string:
                         if (Typetag == 1)
                         {
                             eleNode.ReadValue = visiblestring.AnalizeConvert(frameData, ref errorinfo);
                         }
                         else
                            iResult = visiblestring.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.utf8_string:                      
                         iResult = UTF8string.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.integer:
                         iResult = integer.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.Long:
                         iResult = ilong.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.double_long:
                         iResult = doublelong.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.long64:
                         iResult = long64.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.unsigned:
                         iResult = unsigned.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.long_unsigned:
                         iResult = longunsigned.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.double_long_unsigned:
                         iResult = doublelongunsigned.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.long64_unsigned:
                         iResult = long64unsigned.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.Enum:
                         iResult = ProEnum.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.float32:
                     case enumData.float64:
                         iResult = float32.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.date_time:
                         iResult = datetime.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.date:
                         iResult = date.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.time:
                         iResult = time.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;                     
                     case enumData.CAD:
                         iResult = CAD.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;                    
                     case enumData.ScalerUnit:
                         iResult = ScalerUnit.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.SUnit:
                         iResult = SUnit.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.OBIS:
                         iResult = OBIS.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;                    
                     case enumData.COMDCB:
                         iResult = COMDCB.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break; 
                     case enumData.bcd:
                         if (Typetag == 1)
                           iResult = BCD.AnalizeData(eleNode);
                         else
                           iResult = BCD.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
                     case enumData.ModuleParas:
                         iResult = ModuleParas.AnalizeData(ref frameData, eleNode, ref errorinfo);
                         break;
 
                 }

                 if (!string.IsNullOrEmpty(eleNode.ShowFormat))
                     eleNode.ReadValue = Explaindata1(eleNode.ReadValue, InitFormat(eleNode.ShowFormat));

                 //if (!string.IsNullOrEmpty(errorinfo))
                 //    errorinfo += "["
                 //               + oldframedata
                 //               + "]";

                 return iResult;
             }
             catch (Exception ex)
             {
                 errorinfo = "数据有缺损"
                           + "[" 
                           + oldframedata
                           + "]";
                 return -1;
             }
        }

        /// <summary>
        /// 将数据按****.**的格式分解
        /// </summary>
        /// <param name="datastr">原始数据</param>
        /// <param name="format">数据格式</param>
        /// <returns></returns>
        public static string Explaindata1(string datastr, string format)
        {
            if (string.IsNullOrEmpty(datastr))
                return string.Empty;
            if (string.IsNullOrEmpty(format))
                return datastr;
            int p = -1;
            StringBuilder formatstr = new StringBuilder(format);

            for (int i = 0; i < formatstr.Length; i++)
            {
                if (formatstr[i] == '*')
                {
                    p++;
                    if (datastr.Length <= p)
                        break;
                    formatstr.Replace("*", datastr[p].ToString(), i, 1);
                }

            }
            return formatstr.ToString();
        }

        /// <summary>
        /// 把数据格式中其他格式统一为*的格式
        /// </summary>
        /// <param name="formatstr"></param>
        /// <returns></returns>
        public static string InitFormat(string formatstr)
        {
            formatstr = formatstr.ToUpper();
            StringBuilder format = new StringBuilder(formatstr);
            format.Replace('Y', '*');
            format.Replace('M', '*');
            format.Replace('D', '*');
            format.Replace('W', '*');
            format.Replace('H', '*');
            format.Replace('h', '*');
            format.Replace('m', '*');
            format.Replace('S', '*');
            format.Replace('F', '*');
            format.Replace('X', '*');
            format.Replace('N', '*');
            format.Replace('L', '*');
            format.Replace('T', '*');
            return format.ToString();
        }
    }

    public class ProEnum 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string value = "";
                if (eleNode.eleNodeList.Count > 0)//有子节点,按子节点位解析数据
                {
                    for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                    {
                        int BitLen = 1;
                        if (!string.IsNullOrEmpty(eleNode.eleNodeList[i].DataLen))
                        {
                            BitLen = int.Parse(eleNode.eleNodeList[i].DataLen);
                            if (BitLen == 0)
                                BitLen = 1;
                        }
                        value += eleNode.eleNodeList[i].SetValue.PadLeft(BitLen, '0');
                    }
                    value = MyConvert.BinToHex(value, 2);

                    //for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                    //    value += string.IsNullOrEmpty(eleNode.eleNodeList[i].SetValue) ? "0" : eleNode.eleNodeList[i].SetValue;
                    //value = MyConvert.BinToHex(value, 2);

                }
                else
                {
                    //shaunwang 2016-9-23 改成传入为十进制 
                    value = MyConvert.DecToHex(eleNode.SetValue, 2);
                    if (value == null)
                        value = eleNode.SetValue;
                }
                return value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string value = eleNode.FrameValue = frameData.Substring(0, 2);
                if (eleNode.eleNodeList.Count > 0)//有子节点,按子节点位解析数据
                {
                    value = MyConvert.HexToBin(value);
                    int bitIndex = 0;
                    for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                    {
                        if (bitIndex == eleNode.eleNodeList.Count) break;
                        int BitLen = 1;
                        if (!string.IsNullOrEmpty(eleNode.eleNodeList[i].DataLen))
                        {
                            BitLen = int.Parse(eleNode.eleNodeList[i].DataLen);
                            if (BitLen == 0)
                                BitLen = 1;
                        }
                        string bitvalue = value.Substring(bitIndex, BitLen);
                        eleNode.eleNodeList[i].ReadValue = bitvalue;
                        bitIndex += BitLen;
                    }
                }
                //else
               // {
                    //eleNode.ReadValue = eleNode.FrameValue;
                eleNode.ReadValue = MyConvert.HexToDec(eleNode.FrameValue);//.PadLeft(2, '0'); //shaunwang 2016-9-23 改成解析为十进制
              //  }
                frameData = frameData.Substring(2);
                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }

        }
    }

    public class Bool 
    {

        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string value = eleNode.SetValue;
             
                value = MyConvert.DecToHex(value, 2);  //shaunwang 2016-11-30

                return value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            try
            {
                int ibool = MyConvert.getInt32(MyConvert.HexToDec(frameData.Substring(0, 2)));  //shaunwang 2016-11-30
                if (ibool > 1)  //统一成0为false,1大于1的都为1便于数据库和显示为true
                    ibool = 1;
                eleNode.ReadValue = ibool.ToString();
                eleNode.FrameValue = ibool.ToString();
                frameData = frameData.Substring(2);  //shaunwang 2016-11-30
                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }

        }

        public static bool AnalizeData(ref string frameData,ref string errorinfo)
        {
            try
            {
                bool fbool = Convert.ToUInt32(frameData.Substring(0, 2), 16) >= 1;
                
                frameData = frameData.Substring(2);  
                return fbool;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return false;
            }

        }

    }

    /// <summary>
    ///  有负数的数据，有符号数据
    /// </summary>
    public class integerData 
    {
        public static int mDlen = 2;
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                int Dlen = mDlen;
                double min = Math.Pow(-2, (Dlen * 8 - 1));
                double max = Math.Pow(2, (Dlen * 8 - 1)) - 1;
                int Scaler = 0;
                try
                {
                    Scaler = Convert.ToInt32(eleNode.Scaler);
                }
                catch (Exception ex) { };
               
                string value = eleNode.SetValue;

                if (string.IsNullOrEmpty(value))
                    value = "0";
                Dlen = Dlen * 2;
                double Dvalue = Convert.ToDouble(value) / Math.Pow(10, Scaler);
                long dd = Convert.ToInt64(Dvalue); //四舍五入

                if (dd > max || dd < min) {
                    errorinfo = "输入数据超出范围" + min.ToString() + ":" + max.ToString();
                    return string.Empty;
                }
                
                if (Dvalue < 0)
                {
                    value = Convert.ToString(dd, 16);
                    value = value.Length > Dlen ? value.Substring(value.Length - Dlen, Dlen) : value.PadLeft(Dlen, 'F');
                }
                else
                {                    
                   value = Convert.ToString(dd, 16).PadLeft(Dlen, '0');                          
                }

                //if (value.Length > Dlen)
                //{
                //    errorinfo = "输入数据超出范围");
                //}
                return value.ToUpper();

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                //string sDlen = eleNode.DataLen;
                int Dlen = mDlen;//string.IsNullOrEmpty(sDlen) ? mDlen : Convert.ToInt32(sDlen);             

                string scaler = eleNode.Scaler;  //换算  shaunwang 2016-8-22
                double iscaler = 0;
                try
                {
                    if (!string.IsNullOrEmpty(scaler))
                        iscaler = Math.Pow(10, Convert.ToDouble(scaler));                      
                }
                catch
                {
                }
                string value = frameData.Substring(0, Dlen * 2);
                eleNode.FrameValue = value;
                switch (Dlen)
                {
                    case 1: value = (Convert.ToSByte(value, 16) * iscaler).ToString(); break;
                    case 2: value = (Convert.ToInt16(value, 16) * iscaler).ToString(); break;
                    case 4: value = (Convert.ToInt32(value, 16) * iscaler).ToString(); break;
                    case 8: value = (Convert.ToInt64(value, 16) * iscaler).ToString(); break;
                }
               
                //if (iscaler !=1) //补充足够位小数位
                //{
                //    int pp = value.IndexOf('.');
                //    int declen = pp > 0 ? value.Length - pp - 1 : 0;
                //    if (pp < 0)
                //        value = value + ".";
                //    for (int i = declen; i < Math.Abs(int.Parse(scaler)); i++)
                //        value = value + "0";
                       
                //}
                eleNode.ReadValue = value;

                frameData = frameData.Substring(Dlen * 2);
                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
    }
    
    public class integer 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            integerData.mDlen = 1;
            return integerData.GetFormatValue(eleNode,ref errorinfo);

        }
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            integerData.mDlen = 1;
            return integerData.AnalizeData(ref frameData, eleNode, ref errorinfo);
        }

    }

    public class ilong 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            integerData.mDlen = 2;
            return integerData.GetFormatValue(eleNode,ref errorinfo);

        }
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            integerData.mDlen = 2;
            return integerData.AnalizeData(ref frameData, eleNode, ref errorinfo);
        }

    }

    public class doublelong 
    {

        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            integerData.mDlen = 4;
            return integerData.GetFormatValue(eleNode,ref errorinfo);

        }
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            integerData.mDlen = 4;
            return integerData.AnalizeData(ref frameData, eleNode, ref errorinfo);
        }

    }
    public class long64 : ilong
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            integerData.mDlen = 8;
            return integerData.GetFormatValue(eleNode,ref errorinfo);

        }
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            integerData.mDlen = 8;
            return integerData.AnalizeData(ref frameData, eleNode, ref errorinfo);
        }
    }

    /// <summary>
    /// 无符号数据解析
    /// </summary>
    public class unsignedData 
    {
        public static int mDlen = 1;
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string value = "";
                int Dlen = mDlen;

                if (eleNode.eleNodeList.Count > 0)//有子节点,按子节点位组成数据
                {
                    for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                    {
                        int BitLen = 1;
                        if (!string.IsNullOrEmpty(eleNode.eleNodeList[i].DataLen))
                        {
                            BitLen = int.Parse(eleNode.eleNodeList[i].DataLen);
                            if (BitLen == 0)
                                BitLen = 1;
                        }
                        value += eleNode.eleNodeList[i].SetValue.PadLeft(BitLen, '0');
                    }
                    value = value.PadRight(Dlen * 8, '0');  //2019-6-25 右边补0
                    value = MyConvert.BinToHex(value, mDlen * 2);
                }
                else
                {
                    double min = 0;
                    double max = Math.Pow(2, Dlen * 8) - 1;
                    int Scaler = 0;
                    try
                    {
                       Scaler = Convert.ToInt32(eleNode.Scaler);
                    }
                    catch(Exception ex){};

                    value = eleNode.SetValue;
                    if (string.IsNullOrEmpty(value))
                        value = "0";
                    double Dvalue = Convert.ToDouble(value) / Math.Pow(10, Scaler);
                    long d = Convert.ToInt64(Dvalue); //四舍五入

                    if (d<min || d>max)
                    {
                        errorinfo = "输入数据超出范围" + min.ToString() + ":" + max.ToString();
                        return string.Empty;
                    }
                    value = Convert.ToString(d, 16).PadLeft(Dlen * 2, '0');
                    
                }

                return value.ToUpper();

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                //string sDlen = eleNode.DataLen;
                int Dlen = mDlen;// string.IsNullOrEmpty(sDlen) ? mDlen : Convert.ToInt32(sDlen);

                string scaler = eleNode.Scaler;  //换算  shaunwang 2016-8-22
                double iscaler = 0;                
                try
                {
                    if (!string.IsNullOrEmpty(scaler))
                        iscaler = Math.Pow(10, Convert.ToDouble(scaler));                        
                }
                catch
                {
                }
                string value = frameData.Substring(0, Dlen * 2);
                eleNode.FrameValue = value;
                eleNode.ReadValue = value;
                if (eleNode.eleNodeList.Count > 0)//有子节点,按子节点位解析数据
                {
                    value = MyConvert.HexToBin(value);
                    int bitIndex = 0;
                    for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                    {
                       // if (bitIndex == eleNode.eleNodeList.Count) break;
                        int BitLen = 1;
                        if (!string.IsNullOrEmpty(eleNode.eleNodeList[i].DataLen))
                        {
                            BitLen = int.Parse(eleNode.eleNodeList[i].DataLen);
                            if (BitLen == 0)
                                BitLen = 1;
                        }
                        string bitvalue = value.Substring(bitIndex, BitLen);
                        eleNode.eleNodeList[i].ReadValue = bitvalue;
                        bitIndex += BitLen;
                    }
                }
                else
                {
                    switch (Dlen)
                    {
                        case 1:
                        case 2: value = (Convert.ToUInt16(value, 16) * iscaler).ToString(); break;
                        case 4: value = (Convert.ToUInt32(value, 16) * iscaler).ToString(); break;
                        case 8: value = (Convert.ToUInt64(value, 16) * iscaler).ToString(); break;
                    }
                    //if (iscaler != 1) //补充足够位小数位
                    //{
                    //    int pp = value.IndexOf('.');
                    //    int declen = pp > 0 ? value.Length - pp - 1 : 0;
                    //    if (pp < 0)
                    //        value = value + ".";
                    //    for (int i = declen; i < Math.Abs(int.Parse(scaler)); i++)
                    //        value = value + "0";

                    //}
                    eleNode.ReadValue = value;
                }                

                frameData = frameData.Substring(Dlen * 2); 
                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
    }
    
    public class unsigned 
    {
        //public static int mDlen = 1;
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            unsignedData.mDlen = 1;
            return unsignedData.GetFormatValue(eleNode,ref errorinfo);

        }
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            unsignedData.mDlen = 1;
            return unsignedData.AnalizeData(ref frameData, eleNode, ref errorinfo);
        }
    }

    public class longunsigned 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            unsignedData.mDlen = 2;
            return unsignedData.GetFormatValue(eleNode,ref errorinfo);

        }
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            unsignedData.mDlen = 2;
            return unsignedData.AnalizeData(ref frameData, eleNode, ref errorinfo);
        }
    }
    public class doublelongunsigned 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            unsignedData.mDlen = 4;
            return unsignedData.GetFormatValue(eleNode,ref errorinfo);

        }
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            unsignedData.mDlen = 4;
            return unsignedData.AnalizeData(ref frameData, eleNode, ref errorinfo);
        }
    }
    public class long64unsigned 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            unsignedData.mDlen = 8;
            return unsignedData.GetFormatValue(eleNode,ref errorinfo);

        }
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            unsignedData.mDlen = 8;
            return unsignedData.AnalizeData(ref frameData, eleNode, ref errorinfo);
        }
    }

    /// <summary>
    /// 浮点数处理，符号国际IEEE标准
    /// </summary>
    public class float32 
    {
        public static int mDlen = 4;
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                
                int Scaler = Convert.ToInt32(eleNode.Scaler);
                string value = eleNode.SetValue;
                int Dlen = string.IsNullOrEmpty(eleNode.DataLen) ? mDlen : Convert.ToInt32(eleNode.DataLen);

                byte[] Buf = BitConverter.GetBytes((float)Convert.ToDouble(value));
                value = MyConvert.ByteArrayToHexString(Buf, Dlen);
                value = ProtocolRelated.ChangeAddress(value);
                return value;

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                string sDlen = eleNode.DataLen;
                int Dlen = string.IsNullOrEmpty(sDlen) ? mDlen : Convert.ToInt32(sDlen);

                string value = frameData.Substring(0, Dlen * 2);
                eleNode.FrameValue = value;

                value = ProtocolRelated.ChangeAddress(value);
                byte[] buf = MyConvert.HexStringToByteArray(value);
                float fvalue = BitConverter.ToSingle(buf, 0);

                eleNode.ReadValue = fvalue.ToString();

                frameData = frameData.Substring(Dlen * 2);
                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
    }
    //public class float64 : float32 { }
    public class bstring 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {            
                
                int BitLen = 0;
                try
                {
                    BitLen = Convert.ToInt32(eleNode.DataLen);
                }
                catch (Exception ex)
                {
                }
                
                int Dlen = Convert.ToInt32(Math.Ceiling((decimal)BitLen / 8));
                if (Dlen == 0)
                {
                    Dlen = eleNode.SetValue.Length / 2;
                }
                string value = "";// eleNode.SetValue;               

                if (value == "" && eleNode.eleNodeList.Count > 0)  //参数在子节点中
                {
                    for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                    {
                        if (eleNode.eleNodeList[i].SetValue == "")
                            value += "0";
                        else
                            value += eleNode.eleNodeList[i].SetValue;
                    }                   
                }
                else
                    value = eleNode.SetValue;

                value = value.Length >= Dlen * 8 ? value.Substring(0, Dlen * 8) : value.PadRight(Dlen * 8, '0');//bitstring是在右边补齐

                value = MyConvert.BinToHex(value, Dlen * 2);              
                eleNode.SetValue = value;               
                return BERiLen.GetFormatValue(Dlen * 8) + value;　//命令中传位数
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 直接根据字符串生成命令串
        /// </summary>
        /// <param name="eleValue"></param>
        /// <returns></returns>
        public static string GetFormatValue(string eleValue, ref string errorinfo)
        {
            try
            {
               // int DLen = eleValue.Length;                            

               // string value = DLen % 2 == 0 ? eleValue : "0" + eleValue;

               //// return MyConvert.DecToHex((eleValue.Length / 2 * 8).ToString(), 2) + value;
               // return BERiLen.GetFormatValue(eleValue.Length / 2 * 8) + value;
                int BitLen = eleValue.Length;
                int Dlen = Convert.ToInt32(Math.Ceiling((decimal)BitLen / 8));
                eleValue = eleValue.Length >= Dlen * 8 ? eleValue.Substring(0, Dlen * 8) : eleValue.PadRight(Dlen * 8, '0');//bitstring是在右边补齐
                string value = MyConvert.BinToHex(eleValue, Dlen * 2);

                return BERiLen.GetFormatValue(eleValue.Length) + value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 直接根据字符串和长度生成命令串
        /// </summary>
        /// <param name="eleValue"></param>
        /// <returns></returns>
        public static string GetFormatValue(string eleValue, string dlen, ref string errorinfo)
        {
            try
            {
                int DLen = int.Parse(dlen);

                eleValue = eleValue.Length >= DLen * 2 ? eleValue.Substring(0, DLen * 2) : eleValue.PadLeft(DLen * 2, '0');

                return eleValue;

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }


        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                //int Dlen = BERiLen.AnalizeData(ref frameData, ref errorinfo);
                //if (Dlen < 0)
                //{
                //    return -1;
                //}

                //Dlen = Dlen / 8;//命令中传的是位数,转成字节数
                //string value = frameData.Substring(0, Dlen * 2);
                //frameData = frameData.Substring((Dlen) * 2);//数据长度加1字节长度字节

                //eleNode.ReadValue = value;
                //eleNode.FrameValue = value;

                //string bitstring = MyConvert.HexToBin(value).PadLeft(Dlen * 8, '0');
                //for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                //{
                //    int iResult = AnalizeDataBit(ref bitstring, eleNode.eleNodeList[i], ref errorinfo);

                //    if (iResult != 0)
                //    {
                //        return iResult;
                //    }
                //}
                int Bitlen = BERiLen.AnalizeData(ref frameData, ref errorinfo);
                if (Bitlen < 0)
                {
                    return -1;
                }

                int Dlen = Convert.ToInt32(Math.Ceiling((decimal)Bitlen / 8));//Dlen / 8;//命令中传的是位数,转成字节数
                string value = frameData.Substring(0, Dlen * 2);
                frameData = frameData.Substring((Dlen) * 2);//数据长度加1字节长度字节              

                string bitstring = MyConvert.HexToBin(value);//.PadLeft(Dlen * 8, '0');
                eleNode.ReadValue = bitstring.Substring(0, Bitlen);  //无子节点时是bit位的值
                eleNode.FrameValue = value;
                if (eleNode.eleNodeList.Count > 0)
                {  //参数在子节点中
                    eleNode.ReadValue = value; //有子节点直接传16进制出去,具体bit值分解到子节点
                    for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                    {
                        int iResult = AnalizeDataBit(ref bitstring, eleNode.eleNodeList[i], ref errorinfo);

                        if (iResult != 0)
                        {
                            return iResult;
                        }
                    }
                }
                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }

        public static int AnalizeData(ElementData eleNode)
        {           
            try
            {
                int Dlen = eleNode.ReadValue.Length / 2;//命令中传的是位数,转成字节数
                string errorinfo = "";
                string bitstring = MyConvert.HexToBin(eleNode.ReadValue).PadLeft(Dlen * 8, '0');
                eleNode.ReadValue = bitstring;
                for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                {
                    int iResult = AnalizeDataBit(ref bitstring, eleNode.eleNodeList[i], ref errorinfo);

                    if (iResult != 0)
                    {
                        return iResult;
                    }
                }
                return 0;
            }
            catch (Exception ex)
            {              
                return -1;
            }
        }

        public static int AnalizeDataBit(ref string bitstring, ElementData elementData, ref string errorinfo)
        {
            try
            {
                int Dlen = 1;
                try
                {
                    Dlen = Convert.ToInt32(elementData.DataLen);
                }
                catch (Exception ex)
                {
                }
                if (Dlen == 0) Dlen = 1;
                string value = bitstring.Substring(0, Dlen);
                elementData.ReadValue = value;
                bitstring = bitstring.Remove(0, Dlen);
                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;

            }

        }
        /// <summary>
        /// 直接返回字符串
        /// </summary>
        /// <param name="frameData"></param>
        /// <param name="errorinfo"></param>
        /// <returns></returns>
        public static string AnalizeDataSpecial(ref string frameData, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return string.Empty;
            }
            try
            {
                int Dlen = BERiLen.AnalizeData(ref frameData, ref errorinfo);
                if (Dlen < 0)
                {
                    return string.Empty;
                }

                Dlen = Convert.ToInt32(frameData.Substring(0, 2), 16) / 8;
                string value = frameData.Substring(0, Dlen * 2);
                frameData = frameData.Substring(Dlen * 2);//数据长度
                return value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 对于SEQUENCE中的数据不带长度字节,长度从eleNode中获取     
        /// <returns></returns>
        public static int AnalizeDataSpecial(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                int Dlen = Convert.ToInt32(eleNode.DataLen);
                string value = frameData.Substring(0, Dlen * 2);
                frameData = frameData.Substring(Dlen * 2);//数据长度

                eleNode.FrameValue = value;

                eleNode.ReadValue = value;

                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
    }

    public class octString
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                int DLen =0;
                try
                {
                    DLen = Convert.ToInt32(eleNode.DataLen);
                }
                catch(Exception  ex){                    
                }
                
                string value = eleNode.SetValue;
                if (value.Length % 2 != 0)
                    value = "0" + value;
                if (DLen == 0)
                {
                    DLen = value.Length / 2;
                }
                else
                    value = value.Length >= DLen * 2 ? value.Substring(0, DLen * 2) : value.PadLeft(DLen * 2, '0');

               
                return BERiLen.GetFormatValue(DLen) + value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 直接根据字符串生成命令串
        /// </summary>
        /// <param name="eleValue"></param>
        /// <returns></returns>
        public static string GetFormatValue(string eleValue, ref string errorinfo)
        {
            try
            {
                string value = eleValue.Length % 2 == 0 ? eleValue : "0" + eleValue;
                int DLen = eleValue.Length / 2;
              
                return BERiLen.GetFormatValue(DLen) + value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 直接根据字符串和长度生成命令串
        /// </summary>
        /// <param name="eleValue"></param>
        /// <returns></returns>
        public static string GetFormatValue(string eleValue, string dlen, ref string errorinfo)
        {
            try
            {
                if (eleValue == null) return "";
                int DLen = string.IsNullOrEmpty(dlen) ? 0 : int.Parse(dlen);
                if (eleValue.Length % 2 != 0)
                    eleValue = "0" + eleValue;
                if (DLen == 0)
                {
                    DLen = eleValue.Length / 2;
                }

                eleValue = eleValue.Length >= DLen * 2 ? eleValue.Substring(0, DLen * 2) : eleValue.PadLeft(DLen * 2, '0');

                return eleValue;

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }
        
        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {

                int Dlen = BERiLen.AnalizeData(ref frameData, ref errorinfo);            
                if (Dlen< 0)
                {
                    return -1;
                }

                string value = Dlen*2 >= frameData.Length ? frameData : frameData.Substring(0, Dlen * 2);

                frameData = frameData.Remove(0, value.Length);//数据长度加1字节长度字节

                eleNode.ReadValue = value;
                eleNode.FrameValue = value;

                //if (eleNode.eleNodeList.Count > 0)
                //{
                //    string bitstring = MyConvert.HexToBin(value).PadLeft(Dlen * 8, '0');
                //    for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                //    {
                //        int iResult = bstring.AnalizeDataBit(ref bitstring, eleNode.eleNodeList[i], ref errorinfo);

                //        if (iResult != 0)
                //        {
                //            return iResult;
                //        }
                //    }
                //}

                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;

            }
        }
        /// <summary>
        /// 直接返回字符串
        /// </summary>
        /// <param name="frameData"></param>
        /// <param name="errorinfo"></param>
        /// <returns></returns>
        public static string AnalizeDataSpecial(ref string frameData, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return string.Empty;
            }
            try
            {
                int Dlen = BERiLen.AnalizeData(ref frameData, ref errorinfo);
                if (Dlen < 0)
                {
                    return string.Empty;
                }

                string value = frameData.Substring(0, Dlen * 2);
                frameData = frameData.Substring(Dlen * 2 );//数据长度
                return value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 对于SEQUENCE中的数据不带长度字节,长度从eleNode中获取     
        /// <returns></returns>
        public static int AnalizeDataSpecial(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                int Dlen = Convert.ToInt32(eleNode.DataLen);
                
                string value = frameData.Substring(0, Dlen * 2);
                frameData = frameData.Substring(Dlen * 2);//数据长度

                eleNode.FrameValue = value;

                eleNode.ReadValue = value;

                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
    }

    /// <summary>
    /// ASCII字符串（VisibleString）
    /// </summary>
    public class visiblestring 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                if (string.IsNullOrEmpty(eleNode.SetValue))
                    return "00";

                int DLen = 0;
                try
                {
                    DLen = Convert.ToInt32(eleNode.DataLen);
                }
                catch (Exception ex) {}

                string value = eleNode.SetValue;
                if (DLen == 0)
                    DLen = eleNode.SetValue.Length;

                value = MyConvert.StrToHex(value);
                value = value.Length >= DLen * 2 ? value.Substring(0, DLen * 2) : value.PadRight(DLen * 2, '0');
                //return MyConvert.DecToHex(DLen.ToString(), 2) + value;
                return BERiLen.GetFormatValue(DLen) + value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }

        }

        /// <summary>
        /// 直接根据字符串生成命令串
        /// </summary>
        /// <param name="eleValue"></param>
        /// <returns></returns>
        public static string GetFormatValue(string eleValue, ref string errorinfo)
        {
            try
            {
                if (string.IsNullOrEmpty(eleValue))
                    return "00";

                int DLen = eleValue.Length;
                string value = MyConvert.StrToHex(eleValue);

                //return MyConvert.DecToHex(DLen.ToString(), 2) + value;
                return BERiLen.GetFormatValue(DLen) + value;

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 直接根据字符串和长度生成命令串
        /// </summary>
        /// <param name="eleValue"></param>
        /// <returns></returns>
        public static string GetFormatValue(string eleValue, string dlen, ref string errorinfo)
        {
            try
            {
                if (string.IsNullOrEmpty(dlen))
                    dlen = "0";

                int DLen = int.Parse(dlen);
                if (DLen == 0)
                {
                    DLen = eleValue.Length ;
                }
                string value = "";
                if (string.IsNullOrEmpty(eleValue))
                    value = "00";
                else
                    value = MyConvert.StrToHex(eleValue);
                value = value.Length >= DLen * 2 ? value.Substring(0, DLen * 2) : value.PadRight(DLen * 2, '0');

                return value;

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {                
                int Dlen = BERiLen.AnalizeData(ref frameData, ref errorinfo);
                string value = frameData.Substring(0, Dlen * 2);
                frameData = frameData.Substring(Dlen * 2);//数据长度

                eleNode.FrameValue = value;

                value = MyConvert.HexToStr(value);
                while (value.EndsWith("\0"))
                {
                    value = value.Substring(0, value.Length - 1);
                }
                eleNode.ReadValue = value;

                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
        /// <summary>
        /// 对于SEQUENCE中的数据不带长度字节,长度从eleNode中获取
        /// </summary>
        /// <param name="frameData"></param>
        /// <param name="eleNode"></param>
        /// <param name="errorinfo"></param>
        /// <returns></returns>
        public static int AnalizeDataSpecial(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                int Dlen = Convert.ToInt32(eleNode.DataLen, 16);
                
                string value = frameData.Substring(0, Dlen * 2);
                frameData = frameData.Substring(Dlen * 2);//数据长度

                eleNode.FrameValue = value;
                
                value = MyConvert.HexToStr(value);
                while (value.EndsWith("\0"))
                {
                    value = value.Substring(0, value.Length - 1);
                }
                eleNode.ReadValue = value;

                return 0;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }

        /// <summary>
        /// 直接根据字符串本身解析
        /// </summary>
        /// <param name="frameData"></param>
        /// <param name="eleNode"></param>
        /// <param name="errorinfo"></param>
        /// <returns></returns>
        public static string AnalizeConvert(string frameData, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return string.Empty;
            }
            try
            {          
               string value = MyConvert.HexToStr(frameData);
               while (value.EndsWith("\0"))
               {
                   value = value.Substring(0, value.Length - 1);
               }
               return value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }
    }

    public class UTF8string  {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            return string.Empty;
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            return 0;
        }
    }
    
    public class datetime 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        { 
            try
            {
                string value = eleNode.SetValue;
                value = value.Replace("-", "").Replace(":", "").Replace(" ", "");
                while (value.Length < (int)DataTypeLen.date_time * 2)
                    value += "0";               
                
                StringBuilder strb = new StringBuilder();

                strb.Append(date.GetFormatValue(value.Substring(0, (int)DataTypeLen.date * 2), ref errorinfo));
                value = value.Substring((int)DataTypeLen.date * 2);

                strb.Append(time.GetFormatValue(value.Substring(0, (int)DataTypeLen.time * 2), ref errorinfo));
                value = value.Substring((int)DataTypeLen.time * 2);

                strb.Append(value.Substring(0, 6));               
              
                value = strb.ToString();
               
                return value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }


        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {//到时与界面配合再调整方式
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                string value = frameData.Substring(0, (int)DataTypeLen.date_time * 2);
                eleNode.FrameValue = value;

                ElementData ele = new ElementData();
                date.AnalizeData(ref frameData, ele, ref errorinfo);
                string Date = ele.ReadValue;

                time.AnalizeData(ref frameData, ele, ref errorinfo);
                string Time = ele.ReadValue;
               
                eleNode.ReadValue = Date + Time;

                eleNode.ReadValue += frameData.Substring(0, 6);
                frameData = frameData.Remove(0, 6);

                //if (frameData.Substring(0, 4) == "8000")
                //{
                //   eleNode.ReadValue += frameData.Substring(0, 4);
                //   frameData = frameData.Remove(0, 4);
                //}
                //else
                //{
                //    ilong.AnalizeData(ref frameData, ele, ref errorinfo);
                //    eleNode.ReadValue += ele.ReadValue;
                //}

                //unsigned.AnalizeData(ref frameData, ele, ref errorinfo);
                // eleNode.ReadValue += ele.ReadValue;

                return 0;

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
    }

    public class date 
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {          
     
            return GetFormatValue(eleNode.SetValue,ref errorinfo);
        }



        public static string GetFormatValue(string value, ref string errorinfo)
        {
            try
            {
                value = value.Replace("-", "").Replace(":", "").Replace(" ", "").ToUpper();
                while (value.Length < (int)DataTypeLen.date * 2)
                    value += "0";

                StringBuilder strb = new StringBuilder();
                if (value.Substring(0, 4) == "FFFF")//年
                {
                    strb.Append("FFFF");
                }
                else
                {
                    strb.Append(MyConvert.DecToHex(value.Substring(0, 4), 4));
                }

                string tmpstr = value.Substring(4, 2);
                if (tmpstr == "FF" || tmpstr == "FD" || tmpstr == "FE")//月
                {
                    strb.Append(tmpstr);
                }
                else
                {
                    strb.Append(MyConvert.DecToHex(value.Substring(4, 2), 2));
                }

                tmpstr = value.Substring(6, 2);                
                //if (tmpstr == "FF" || tmpstr == "FD" || tmpstr == "FE")//日
                if (int.Parse(MyConvert.HexToDec(tmpstr)) >= 0xE0)
                {
                    strb.Append(tmpstr);
                }
                else
                {
                    strb.Append(MyConvert.DecToHex(value.Substring(6, 2), 2));
                }

                if (value.Substring(8, 2) == "FF")//周
                {
                    strb.Append("FF");
                }
                else
                {
                    strb.Append(MyConvert.DecToHex(value.Substring(8, 2), 2));
                }
                value = strb.ToString();

                return value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }



        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                string value = frameData.Substring(0, (int)DataTypeLen.date * 2);
                eleNode.FrameValue = value;               

                StringBuilder strb = new StringBuilder();
                if (value.Substring(0, 4) == "FFFF")//年
                {
                    strb.Append("FFFF");
                }
                else
                {
                    strb.Append(MyConvert.HexToDec(value.Substring(0, 4)).PadLeft(4, '0'));
                }

                string tmpstr = value.Substring(4, 2);
                if (tmpstr == "FF" || tmpstr == "FD" || tmpstr == "FE")//月
                {
                    strb.Append(tmpstr);
                }
                else
                {
                    strb.Append(MyConvert.HexToDec(value.Substring(4, 2)).PadLeft(2, '0'));
                }

                tmpstr = value.Substring(6, 2);
               // if (tmpstr == "FF" || tmpstr == "FD" || tmpstr == "FE")//日
                if (int.Parse(MyConvert.HexToDec(tmpstr)) >= 0xE0)
                {
                    strb.Append(tmpstr);
                }
                else
                {
                    strb.Append(MyConvert.HexToDec(value.Substring(6, 2)).PadLeft(2, '0'));
                }

                if (value.Substring(8, 2) == "FF")//周
                {
                    strb.Append("FF");
                }
                else
                {
                    strb.Append(MyConvert.HexToDec(value.Substring(8, 2)).PadLeft(2, '0'));
                }
                value = strb.ToString();

                frameData = frameData.Substring((int)DataTypeLen.date * 2);

                eleNode.ReadValue = value;
                return 0;

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
    }
    public class time
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            return GetFormatValue(eleNode.SetValue,ref errorinfo);
        }
        public static string GetFormatValue(string value, ref string errorinfo)
        {
            try
            {
                value = value.Replace("-", "").Replace(":", "").Replace(" ", "").ToUpper();
               
                StringBuilder strb = new StringBuilder();               
                for (int i = 0; i < value.Length / 2; i++)
                {
                    if (value.Substring(i * 2, 2) == "FF")//时
                    {
                        strb.Append("FF");
                    }
                    else
                    {
                        strb.Append(MyConvert.DecToHex(value.Substring(i * 2, 2), 2));
                    }                  
                }
                
                value = strb.ToString();

                return value;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }



        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            if (string.IsNullOrEmpty(frameData))
            {
                return -1;
            }
            try
            {
                int dlen =(int)DataTypeLen.time * 2;
                //if (eleNode.DataLen != null && int.Parse(eleNode.DataLen) != 0)
                if (!string.IsNullOrEmpty(eleNode.DataLen) && int.Parse(eleNode.DataLen) != 0)  //shaunwang 2019-1-24 出现了eleNode.DataLen=""的情况  会导致报错 
                    dlen = int.Parse(eleNode.DataLen) * 2;
                string value = frameData.Substring(0, dlen);
                eleNode.FrameValue = value;
               
                StringBuilder strb = new StringBuilder();
                for (int i = 0; i < value.Length / 2; i++)
                {
                    if (value.Substring(i * 2, 2) == "FF")//时
                    {
                        strb.Append("FF");
                    }
                    else
                    {
                        strb.Append(MyConvert.HexToDec(value.Substring(i * 2, 2)).PadLeft(2, '0'));
                    }
                }
                //if (value.Substring(0, 2) == "FF")//时
                //{
                //    strb.Append("FF");
                //}
                //else
                //{
                //    strb.Append(MyConvert.HexToDec(value.Substring(0, 2)).PadLeft(2, '0') );
                //}

                //if (value.Substring(2, 2) == "FF")//分
                //{
                //    strb.Append("FF");
                //}
                //else
                //{
                //    strb.Append(MyConvert.HexToDec(value.Substring(2, 2)).PadLeft(2, '0'));
                //}

                //if (value.Substring(4, 2) == "FF")//秒
                //{
                //    strb.Append("FF");
                //}
                //else
                //{
                //    strb.Append(MyConvert.HexToDec(value.Substring(4, 2)).PadLeft(2, '0'));
                //}
                //if (value.Substring(6, 2) == "FF")//hundredths秒
                //{
                //    strb.Append("FF");
                //}
                //else
                //{
                //    strb.Append(MyConvert.HexToDec(value.Substring(6, 2)).PadLeft(2, '0'));
                //}
                value = strb.ToString();
                frameData = frameData.Substring(dlen);

                eleNode.ReadValue = value;
                return 0;

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
    }
    
    public class Array 
    {

        /// <summary>
        /// 正常的按Node子节信息组织数据,数据不带类型和个数,只组织纯数据,满足加密前数据准备
        /// </summary>
        /// <param name="sDataXml"></param>
        /// <returns></returns>
        public static string GetPreFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string FormatValue = string.Empty;

                if (eleNode.eleNodeList.Count == 0)
                {
                    FormatValue = GetFormatValueArray(eleNode,ref errorinfo);
                    return FormatValue;
                }
                else
                {
                    int eleNum = 0;
                    for (eleNum = 0; eleNum < eleNode.eleNodeList.Count; eleNum++)
                    {
                        ElementData childNode = eleNode.eleNodeList[eleNum];
                        if (string.IsNullOrEmpty(childNode.SetValue))
                            break;
                        FormatValue = FormatValue + Data.GetPreFormatValue(childNode,0,ref errorinfo);
                    }
                    return FormatValue;
                }

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 正常的按Node子节信息组织数据
        /// </summary>
        /// <param name="sDataXml"></param>
        /// <returns></returns>
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string FormatValue = string.Empty;

                if (eleNode.eleNodeList.Count == 0)
                {
                    FormatValue = GetFormatValueArray(eleNode,ref errorinfo);
                    return FormatValue;
                }
                else
                {
                    
                    int eleNum = 0;                   
                    for (eleNum = 0; eleNum < eleNode.eleNodeList.Count; eleNum++)
                    {                        
                        ElementData childNode = eleNode.eleNodeList[eleNum];
                        //if (string.IsNullOrEmpty(childNode.SetValue) && eleNum == 0)
                        //{
                        //    errorinfo = "未输入任何数据,请输入正确的设置参数");
                        //}
                        if (!ChildExistValue(childNode)) //hxh 2019-4-26 如节点设置数据为空,退出. 满足设置几个就发几个
                            break;
                        string svalue = Data.GetFormatValue(childNode, ref errorinfo);
                       
                        FormatValue = FormatValue + svalue;                        
                    }

                  //最后加上结构元素个数
                    return BERiLen.GetFormatValue(eleNum) + FormatValue;
                }
                
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取所有子节点的输入值拼起来
        /// </summary>
        public static bool ChildExistValue(ElementData eleNode)
        {
            if (!string.IsNullOrEmpty(eleNode.SetValue))
                return true;

            bool HaveValue = false;
            for (int i = 0; i < eleNode.eleNodeList.Count; i++)
            {
                if (!string.IsNullOrEmpty(eleNode.eleNodeList[i].SetValue))
                    return true;
                HaveValue = ChildExistValue(eleNode.eleNodeList[i]); 
            }

            return HaveValue;
        }

        /// <summary>
        /// Array中子节点数据简单，直接在界面层组织好子数据逗号隔开传入
        /// </summary>
        /// <param name="sDataXml"></param>
        /// <returns></returns>
        public static string GetFormatValueArray(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                if (string.IsNullOrEmpty(eleNode.SetValue))
                    return "00";
                string[] value = eleNode.SetValue.Split(',');
                int eleNum = value.Length;
               
                return BERiLen.GetFormatValue(eleNum) + eleNode.SetValue.Replace(",", "");

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            int iResult = 0;
            try
            {
                string value = frameData;
                int strucNum = BERiLen.AnalizeData(ref frameData, ref  errorinfo);
                if (strucNum == 0) return iResult;

                List<string> readValue = new List<string>();
                if (eleNode.eleNodeList == null || eleNode.eleNodeList.Count == 0)  //子节点个数为零时,子节点全新生成
                {
                    for (int i = 0; i < strucNum; i++)
                    {
                        ElementData ele = new ElementData(); //用父节点的换算
                        ele.Scaler = eleNode.Scaler;                        
                        eleNode.eleNodeList.Add(ele);
                    }
                }
                                        
                List<ElementData> NodeList = eleNode.eleNodeList;
                int NodelistCount = NodeList.Count;
                ElementData LastNode = NodeList[NodelistCount - 1].DeepClone();//最后一个子节点，当数据未解完但无子节点时取最后一个子节点数据解析
                LastNode.ClearEleParams(true); //清空一下抄读设置等参数,以免下面出错时显示用的还是复制节点里的数据
                string ReadValue = string.Empty;
                for (int i = 0; i < strucNum; i++)
                {
                    //Application.DoEvents();
                    //Thread.Sleep(2);
                    if (i >= NodeList.Count)
                    {
                        ElementData tmpNode = (ElementData)LastNode.DeepClone();//最后一个节点客隆一个                        
                        iResult = Data.AnalizeData(ref frameData, tmpNode, ref errorinfo);
                        tmpNode.ValueName += i + 1;
                        eleNode.eleNodeList.Add(tmpNode);
                        ReadValue = tmpNode.ReadValue;                        
                       // readValue.Add("\r{" + ReadValue + "}");//
                        readValue.Add(ReadValue);//
                    }
                    else
                    {
                        iResult = Data.AnalizeData(ref frameData, eleNode.eleNodeList[i], ref errorinfo);
                        eleNode.eleNodeList[i].ValueName += i + 1;
                        ReadValue = eleNode.eleNodeList[i].ReadValue;                        
                        //if (i == 0)
                        //    readValue.Add("{" + ReadValue + "}");
                        //else
                        //    readValue.Add("\r{" + ReadValue + "}"); // 
                       // if (i == 0)
                            readValue.Add(ReadValue);
                       // else
                       //     readValue.Add("\r" + ReadValue); // 
                    }

                    if (iResult < 0) 
                        break;
                }
                if (strucNum < NodelistCount)  //返回个数少于带下来的数据节点个数时，把剩余的节点删除
                {
                    for (int j = NodelistCount; j > strucNum; j--)
                    {
                        NodeList.Remove(NodeList[NodeList.Count - 1]);
                    }
                }
                

                eleNode.FrameValue = value.Substring(0, value.Length - frameData.Length);//父节点保存完整数组数据
                eleNode.ReadValue = string.Join(",", readValue.ToArray());
                eleNode.ReadValue = "{" + eleNode.ReadValue + "}";
                eleNode.DataLen = strucNum.ToString();  //父节点长度保存此次回来的元素个数
                return iResult;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
    }

    public class Structure  {
        /// <summary>
        /// 正常的按Node子节信息组织数据,数据不带类型和个数,只组织纯数据,满足加密前数据准备
        /// </summary>
        /// <param name="sDataXml"></param>
        /// <returns></returns>
        public static string GetPreFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string FormatValue = string.Empty;

                if (eleNode.eleNodeList.Count == 0)
                {
                    FormatValue = GetFormatValueArray(eleNode,ref errorinfo);
                    return FormatValue;
                }
                else
                {
                    int eleNum = eleNode.eleNodeList.Count;

                    foreach (ElementData childNode in eleNode.eleNodeList)
                    {
                        FormatValue = FormatValue + Data.GetPreFormatValue(childNode,0,ref errorinfo);
                    }
                    return FormatValue;
                }

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        /// <summary>
        /// 正常的按Node子节信息组织数据
        /// </summary>
        /// <param name="sDataXml"></param>
        /// <returns></returns>
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string FormatValue = string.Empty;

                if (eleNode.eleNodeList.Count == 0)
                {
                    FormatValue = GetFormatValueArray(eleNode,ref errorinfo);
                    return FormatValue;
                }
                else
                {
                    int eleNum = eleNode.eleNodeList.Count;

                    foreach (ElementData childNode in eleNode.eleNodeList)
                    {
                        FormatValue = FormatValue + Data.GetFormatValue(childNode,ref errorinfo);
                    }                   
                    return BERiLen.GetFormatValue(eleNum) + FormatValue;
                }

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }
        /// <summary>
        /// 子节点数据简单，直接在界面层组织好子数据逗号隔开传入
        /// </summary>
        /// <param name="sDataXml"></param>
        /// <returns></returns>
        public static string GetFormatValueArray(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string[] value = eleNode.SetValue.Split(',');
                int eleNum = value.Length;              
                return BERiLen.GetFormatValue(eleNum) + eleNode.SetValue.Replace(",", "");

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            int iResult = 0;
            try
            {
                string value = frameData;

                int strucNum = BERiLen.AnalizeData(ref frameData, ref  errorinfo);
                if (strucNum == 0) return iResult;

                List<string> readValue = new List<string>();
                if (eleNode.eleNodeList == null || eleNode.eleNodeList.Count == 0)//子节点个数为零时,下面子节全新生成   
                {
                    for (int i = 0; i < strucNum; i++)
                    {
                        ElementData ele = new ElementData(); //用父节点的换算
                        ele.Scaler = eleNode.Scaler;
                        eleNode.eleNodeList.Add(ele);
                    }
                }

                List<ElementData> NodeList = eleNode.eleNodeList;
                int NodelistCount = NodeList.Count;
                ElementData LastNode = NodeList[NodelistCount - 1].DeepClone();//最后一个子节点，当数据未解完但无子节点时取最后一个子节点数据解析
                LastNode.ClearEleParams(true);

                for (int i = 0; i < strucNum; i++)                
                {
                    //Application.DoEvents();
                    //Thread.Sleep(2);
                    if (i >= NodeList.Count)
                    {
                        ElementData tmpNode = (ElementData)LastNode.DeepClone();//最后一个节点客隆一个                       
                        iResult = Data.AnalizeData(ref frameData, tmpNode, ref errorinfo);
                        eleNode.eleNodeList.Add(tmpNode);                        
                        readValue.Add(tmpNode.ReadValue);
                    }
                    else
                    {
                        iResult = Data.AnalizeData(ref frameData, eleNode.eleNodeList[i], ref errorinfo);                        
                        readValue.Add(eleNode.eleNodeList[i].ReadValue);
                    }

                    if (iResult < 0) 
                        break;
                }
                eleNode.FrameValue = value.Substring(0, value.Length - frameData.Length);//父节点保存完整数组数据
               // eleNode.FrameValue = string.Join(",", frameValue.ToArray()); //父节点以逗号隔开保存子节点数据
                eleNode.ReadValue = string.Join(",", readValue.ToArray());
                eleNode.ReadValue = "{" + eleNode.ReadValue + "}\r";
                eleNode.DataLen = strucNum.ToString();
                return iResult;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
        }
        
        public static int AnalizeData(ElementData eleNode, ref string errorinfo)
        {
            int iResult = 0;
            try{
                string frameData = eleNode.ReadValue;
                List<string> readValue = new List<string>();
                for (int i = 0; i < eleNode.eleNodeList.Count; i++)
                {
                    //Application.DoEvents();
                    enumData dtype = (enumData)Enum.Parse(typeof(enumData), eleNode.eleNodeList[i].DataType);
                    iResult = Data.AnalizeDtypeData(ref frameData, eleNode.eleNodeList[i], dtype, 1, ref errorinfo);
                    readValue.Add(eleNode.eleNodeList[i].ReadValue);    
                    if (iResult < 0) break;
                }
                eleNode.ReadValue = string.Join(",", readValue.ToArray());
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
            return iResult;
        }
    }
    public class CHOICE
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            int Option = MyConvert.getInt32(eleNode.SetValue);
            if (eleNode.eleNodeList.Count < Option + 1) {
                errorinfo = "对象子节点信息不全";
                return string.Empty;
            }            
            return Data.GetFormatValue(eleNode.eleNodeList[Option],ref errorinfo); 
        }
       
    }

    public class TokenEnterData
    {
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {         

            string hexstr = MyConvert.RandomDecToHex(eleNode.SetValue, 18);
            return "00000001" + hexstr;
        }       
    }


    public class MKEncrypt
    {
        private static string AppendStr = "A6A6A6A6A6A6A6A6";
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            if (Data.encryption.IfEncrypt())
            {
                Data.encryption.PlaintData = eleNode.SetValue + AppendStr; //密钥后加8字节A6

                string Encryptstr = Data.encryption.Aes_wrap_String(Data.encryption.Key.MK, ref errorinfo);

                return Encryptstr;
            }
            else
                return eleNode.SetValue;
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            int iResult = 0;
            try
            {
                eleNode.FrameValue = frameData;
                if (Data.encryption.IfEncrypt())
                {
                    Data.encryption.EncryptData = frameData;
                    string PlaintData = Data.encryption.Aes_unwrap_String(Data.encryption.Key.MK, ref errorinfo);

                    eleNode.ReadValue = PlaintData.Substring(0, PlaintData.Length - AppendStr.Length);
                    iResult = string.IsNullOrEmpty(errorinfo) ? 0 : -1;
                }
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
            return iResult;
        }
    }
        

    public class BCDYYMMDDHHmm
    {
        public static string GetPreFormatValue(ElementData eleNode)
        {
            string value = eleNode.SetValue;
            try
            {                
                while (value.Length < 5 * 2)
                    value += "0";
                value = value.Substring(2, 10);           
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }            
            return value;
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string value = string.Empty;
                value = frameData.Substring(0, 10);

                if (Convert.ToInt64(value) != 0)  //为全0时加00,
                    value = "20" + value;
                else
                    value = "00" + value;
                
                eleNode.ReadValue = value;
                frameData = frameData.Substring(10);
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
            return 0;
        }
    }


    /// <summary>
    /// 封装字节长度，分三种情况
    /// 1.直接1字节长度（0-127）
    /// 2.0x81+1字节长度（128-255）
    /// 3.0x82+2字节长度（256-..）
    /// </summary>
    public class BERiLen
    {
        public static string GetFormatValue(ElementData eleNode)
        {
            string avalue = "";

            return avalue;
        }

        public static string GetFormatValue(int Dlen)
        {
            string avalue = MyConvert.DecToHex(Dlen.ToString(), 2);
            if (Dlen >= 128 && Dlen <= 255)
            {
                avalue = "81" + avalue;
                
            }
            else if (Dlen > 255)
            {
                avalue = "82" + MyConvert.DecToHex(Dlen.ToString(), 4);                
            }
            return avalue;
        }

        public static int AnalizeData(ref string frameData,  ref string  errorinfo)
        {
            try
            {
                int Dlen = Convert.ToInt32(frameData.Substring(0, 2), 16);
                frameData = frameData.Remove(0, 2);

                if (Dlen == Convert.ToInt32("81", 16))
                {                    
                    Dlen = Convert.ToInt32(frameData.Substring(0, 2), 16);
                    frameData = frameData.Remove(0, 2);
                }
                else if (Dlen == Convert.ToInt32("82", 16))
                {
                    Dlen = Convert.ToInt32(frameData.Substring(0, 4), 16);
                    frameData = frameData.Remove(0, 4);
                }
                return Dlen;
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }            
        }
    }

    public class BCD
    {

        public static string GetPreFormatValue(ElementData eleNode, ref string errorinfo)
        {
            return MyConvert.HexToDec(eleNode.SetValue);
        }

        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            int Scaler = 0;
            try
            {
                Scaler = Math.Abs(Convert.ToInt32(eleNode.Scaler));
            }
            catch (Exception ex) { };

           // int Scaler = Math.Abs(Convert.ToInt32(eleNode.Scaler));
            string avalue = eleNode.SetValue;
            if (Scaler > 0)   //对于带小数点的格式处理
            {
                int vindex = avalue.LastIndexOf('.');
                if (vindex < 0)  //输入参数未带小数点  NNN.N  500
                {

                    for (int i = 0; i < Scaler; i++)
                        avalue = avalue + "0";
                }
                else           //输入参数带了小数点
                {
                    string[] valueinfo = avalue.Split('.');
                    string value2 = valueinfo[1].PadRight(Scaler, '0');
                    avalue = valueinfo[0] + value2;
                }
            }
            avalue = avalue.PadLeft(Convert.ToInt32(eleNode.DataLen) * 2, '0');
            return BERiLen.GetFormatValue(avalue.Length / 2) + avalue;
        }

        public static int AnalizeData(ElementData eleNode)
        {
            try
            {
                string value = eleNode.FrameValue;
                int Scaler = 0;
                try
                {
                    Scaler = Math.Abs(Convert.ToInt32(eleNode.Scaler));
                }
                catch (Exception ex) { };
               // int Scaler = Math.Abs(Convert.ToInt32(eleNode.Scaler));

                if (Scaler > 0)
                {
                    value = value.Insert(value.Length - Scaler, ".");
                }
                eleNode.ReadValue = value;                
            }
            catch (Exception ex)
            {               
                return -1;
            }
            return 0;
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string value = string.Empty;
                int Dlen = Convert.ToInt32(eleNode.DataLen);
                value = frameData.Substring(0, Dlen * 2);
                int Scaler = 0;
                try
                {
                    Scaler = Math.Abs(Convert.ToInt32(eleNode.Scaler));
                }
                catch (Exception ex) { };

               // int Scaler = Math.Abs(Convert.ToInt32(eleNode.Scaler));

                if (Scaler > 0)
                {
                    value = value.Insert(value.Length - Scaler, ".");
                }
                eleNode.ReadValue = value;
                frameData = frameData.Substring(Dlen * 2);
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
            return 0;
        }
    }

    public class ModuleParas
    {
        /// <summary>
        /// 正常的按Node子节信息组织数据,数据不带类型和个数,只组织纯数据,满足加密前数据准备
        /// </summary>
        /// <param name="sDataXml"></param>
        /// <returns></returns>
        public static string GetFormatValue(ElementData eleNode, ref string errorinfo)
        {
            try
            {
                string FormatValue = string.Empty;

                if (eleNode.eleNodeList.Count == 0)
                {
                   // FormatValue = GetFormatValueArray(eleNode, ref errorinfo);
                    return FormatValue;
                }
                else
                {
                    int eleNum = eleNode.eleNodeList.Count;
                    FormatValue = eleNode.eleNodeList[0].SetValue ;
                    for (int i = 1; i < eleNum;i++)
                    {
                        FormatValue = FormatValue + Data.GetFormatValue(eleNode.eleNodeList[i], ref errorinfo);
                    }
                    return FormatValue;
                }

            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return string.Empty;
            }
        }

        public static int AnalizeData(ref string frameData, ElementData eleNode, ref string errorinfo)
        {
            int iresult = 0;
            try
            {
               
                string ModulID = frameData.Substring(0, 4);
                frameData = frameData.Substring(4);

                if (eleNode.eleNodeList.Count == 0)
                {
                    eleNode.ReadValue = ModulID + ',';
                    ElementData ele = new ElementData();
                    iresult = Data.AnalizeData(ref frameData, ele, ref errorinfo);
                    eleNode.ReadValue += ele.ReadValue;
                }
                else
                {
                    eleNode.eleNodeList[0].ReadValue = ModulID; //ModulID 2字节
                    
                    for (int i = 1; i < eleNode.eleNodeList.Count; i++)
                        iresult = Data.AnalizeData(ref frameData, eleNode.eleNodeList[i], ref errorinfo);
                }
            }
            catch (Exception ex)
            {
                errorinfo = ex.ToString();
                return -1;
            }
            return iresult;
        }
    }
}
